import { createRouter, createWebHashHistory } from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import Cookies from 'js-cookie'
import type { NavigationGuardNext, RouteLocationNormalized } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'

// 布局组件
const Layout = () => import('@/layout/index.vue')

// 路由配置
export const constantRoutes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: { title: '登录', hidden: true }
  },
  {
    path: '/404',
    name: '404',
    component: () => import('@/views/error-page/404.vue'),
    meta: { title: '404', hidden: true }
  },
  {
    path: '/403',
    name: '403',
    component: () => import('@/views/error-page/403.vue'),
    meta: { title: '403', hidden: true }
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/index.vue'),
        meta: { title: '仪表盘', icon: 'Dashboard', affix: true }
      }
    ]
  }
]

// 动态路由 - 根据权限加载
export const asyncRoutes: Array<RouteRecordRaw> = [
  // 内容管理
  {
    path: '/content',
    component: Layout,
    redirect: '/content/announcement',
    name: 'Content',
    meta: { 
      title: '内容管理', 
      icon: 'Document',
      roles: ['admin', 'editor'],
      permissions: ['content:view']
    },
    children: [
      {
        path: 'announcement',
        name: 'Announcement',
        component: () => import('@/views/content/announcement/index.vue'),
        meta: { 
          title: '公告管理', 
          permissions: ['announcement:view']
        }
      },
      {
        path: 'announcement/add',
        name: 'AnnouncementAdd',
        component: () => import('@/views/content/announcement/edit.vue'),
        meta: { 
          title: '添加公告', 
          hidden: true,
          activeMenu: '/content/announcement',
          permissions: ['announcement:add']
        }
      },
      {
        path: 'announcement/edit/:id',
        name: 'AnnouncementEdit',
        component: () => import('@/views/content/announcement/edit.vue'),
        meta: { 
          title: '编辑公告', 
          hidden: true,
          activeMenu: '/content/announcement',
          permissions: ['announcement:edit']
        }
      },
      {
        path: 'help',
        name: 'Help',
        component: () => import('@/views/content/help/index.vue'),
        meta: { 
          title: '帮助中心', 
          permissions: ['help:view']
        }
      },
      {
        path: 'help/add',
        name: 'HelpAdd',
        component: () => import('@/views/content/help/edit.vue'),
        meta: { 
          title: '添加帮助文档', 
          hidden: true,
          activeMenu: '/content/help',
          permissions: ['help:add']
        }
      },
      {
        path: 'help/edit/:id',
        name: 'HelpEdit',
        component: () => import('@/views/content/help/edit.vue'),
        meta: { 
          title: '编辑帮助文档', 
          hidden: true,
          activeMenu: '/content/help',
          permissions: ['help:edit']
        }
      },
      {
        path: 'carousel',
        name: 'Carousel',
        component: () => import('@/views/content/carousel/index.vue'),
        meta: { 
          title: '轮播图管理', 
          permissions: ['carousel:view']
        }
      },
      {
        path: 'carousel/add',
        name: 'CarouselAdd',
        component: () => import('@/views/content/carousel/edit.vue'),
        meta: { 
          title: '添加轮播图', 
          hidden: true,
          activeMenu: '/content/carousel',
          permissions: ['carousel:add']
        }
      },
      {
        path: 'carousel/edit/:id',
        name: 'CarouselEdit',
        component: () => import('@/views/content/carousel/edit.vue'),
        meta: { 
          title: '编辑轮播图', 
          hidden: true,
          activeMenu: '/content/carousel',
          permissions: ['carousel:edit']
        }
      }
    ]
  },
  
  // 权限管理
  {
    path: '/permission',
    component: Layout,
    redirect: '/permission/role',
    name: 'Permission',
    meta: { 
      title: '权限管理', 
      icon: 'Lock',
      roles: ['admin'],
      permissions: ['permission:view']
    },
    children: [
      {
        path: 'role',
        name: 'Role',
        component: () => import('@/views/permission/role/index.vue'),
        meta: { 
          title: '角色管理', 
          permissions: ['role:view']
        }
      },
      {
        path: 'role/add',
        name: 'RoleAdd',
        component: () => import('@/views/permission/role/edit.vue'),
        meta: { 
          title: '添加角色', 
          hidden: true,
          activeMenu: '/permission/role',
          permissions: ['role:add']
        }
      },
      {
        path: 'role/edit/:id',
        name: 'RoleEdit',
        component: () => import('@/views/permission/role/edit.vue'),
        meta: { 
          title: '编辑角色', 
          hidden: true,
          activeMenu: '/permission/role',
          permissions: ['role:edit']
        }
      },
      {
        path: 'permission',
        name: 'PermissionList',
        component: () => import('@/views/permission/permission/index.vue'),
        meta: { 
          title: '权限控制', 
          permissions: ['permission:config']
        }
      }
    ]
  },
  
  // 系统配置
  {
    path: '/system',
    component: Layout,
    redirect: '/system/basic',
    name: 'System',
    meta: { 
      title: '系统配置', 
      icon: 'Setting',
      roles: ['admin'],
      permissions: ['system:config']
    },
    children: [
      {
        path: 'basic',
        name: 'BasicConfig',
        component: () => import('@/views/system/basic/index.vue'),
        meta: { 
          title: '基础配置', 
          permissions: ['system:basic:view']
        }
      },
      {
        path: 'security',
        name: 'SecurityConfig',
        component: () => import('@/views/system/security/index.vue'),
        meta: { 
          title: '安全配置', 
          permissions: ['system:security:view']
        }
      }
    ]
  },
  
  // 个人中心和个人设置
  {
    path: '/profile',
    component: Layout,
    redirect: '/profile/center',
    name: 'Profile',
    meta: { title: '个人中心', icon: 'User' },
    children: [
      {
        path: 'center',
        name: 'ProfileCenter',
        component: () => import('@/views/profile/center.vue'),
        meta: { title: '个人中心' }
      },
      {
        path: 'setting',
        name: 'ProfileSetting',
        component: () => import('@/views/profile/setting.vue'),
        meta: { title: '个人设置' }
      }
    ]
  },
  
  // 404 页面必须放在最后
  { path: '/:pathMatch(.*)*', redirect: '/404', meta: { hidden: true } }
]

// 创建路由
const router = createRouter({
  history: createWebHashHistory(),
  routes: constantRoutes.concat(asyncRoutes), // 合并所有路由
  scrollBehavior: () => ({ left: 0, top: 0 })
})

// NProgress配置
NProgress.configure({ showSpinner: false })

// 路由守卫优化
const whiteList = ['/login', '/404', '/403']

router.beforeEach((to: RouteLocationNormalized, _from: RouteLocationNormalized, next: NavigationGuardNext) => {
  NProgress.start()
  document.title = `${to.meta.title} - AI助农管理系统`
  const token = Cookies.get('Admin-Token')

  if (token) {
    if (to.path === '/login') {
      next({ path: '/dashboard' })
      NProgress.done()
    } else {
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

// 全局后置守卫
router.afterEach(() => {
  // 结束进度条
  NProgress.done()
})

export default router 